<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\BaseController;
use App\Interfaces\LogInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends BaseController
{

    public function __construct()
    {

    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): JsonResponse
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $remember = $request->input('remember');
        $captcha = $request->input('code');
        $captchaKey = $request->input('key');

        $validate = Auth::attempt(['username'=>$username,'password'=>$password],$remember);

        if (!$validate){
            return $this->apiResult(['code'=>1,'message'=>'用户名或密码错误！']);
        }
        if (!captcha_api_check($captcha,$captchaKey,'flat')){
            return $this->apiResult(['code'=>1,'message'=>'验证码错误！']);
        }
        $user = Auth::user();

        $tokenResult = $user->createToken('Personal Access Token');

        if ($user['status']===1){
            return $this->apiResult(['code'=>1,'message'=>'账号被禁用，请联系管理员！']);
        }

        $result['code'] = 0;
        $result['message'] = '登录成功！';
        $result['data']['access_token'] = 'Bearer '.$tokenResult->plainTextToken;
        return $this->apiResult($result);
    }
}
